#include "widget.h"
#include "ui_widget.h"
#include<QMessageBox>
#include<QNetworkDatagram>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //完成socket后续的初始化
    //一般来说先连接信号槽，再绑定端口号
    this->setWindowTitle("服务器");
    //实例化socket
    socket=new QUdpSocket(this);
    //连接信号槽，处理收到的请求
    connect(socket,&QUdpSocket::readyRead,this,&Widget::processRequest);
    //绑定端口
    bool ret=socket->bind(QHostAddress::Any,8080);
    if(!ret)
    {
        QMessageBox::critical(this,"服务器绑定失败",socket->errorString(),QMessageBox::Ok|QMessageBox::No);
        return;
    }
}

Widget::~Widget()
{
    delete ui;
}

QString Widget::HandlerRequest(QString request)
{
    return request;
}

void Widget::processRequest()
{
    //1.读取请求
    const QNetworkDatagram& requestDatagram=socket->receiveDatagram();
    QString request=requestDatagram.data();
    //2.根据请求计算响应
    const QString &response=HandlerRequest(request);
    //3.把响应写回到客户端
    QNetworkDatagram responseDatagram(response.toUtf8(),requestDatagram.senderAddress(),requestDatagram.senderPort());
    socket->writeDatagram(responseDatagram);
    //4.显示打印日志
    QString log="["+requestDatagram.senderAddress().toString()+":"+QString::number(requestDatagram.senderPort())
            +"req:"+request+",rsp:"+response;
    ui->listWidget->addItem(log);
}

